//
//  ESTagDetailViewController.m
//  Eyeshot
//
//  Created by lanou3g on 15/7/8.
//  Copyright (c) 2015年 eyeshot. All rights reserved.
//

#import "ESTagDetailViewController.h"
#import "ESHeaderView.h"
#import "AFNetworking.h"
#import "ESTopModel.h"
#import "ESListModel.h"
#import "ESTDCollectionViewCell.h"
#import "ESTDPictureCell.h"
#import "ESTDDuanZiCell.h"
#import "ESTDTextAndPicCell.h"
#import "ESTDVideoCell.h"
#import "MoviePlayerViewController.h"
#import "ESTDVoiceCell.h"
#import "ESDT2ViewController.h"
@interface ESTagDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,MoviePlayerViewControllerDataSource>
@property (strong, nonatomic) IBOutlet UITableView *tagDetailTableView;
@property (strong,nonatomic) ESHeaderView *headerView;
@property (strong,nonatomic) NSMutableArray *topArray;//头视图数据数组
@property (strong,nonatomic) NSMutableArray *listArray;//表视图数据数组
@end

@implementation ESTagDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    self.view.backgroundColor = [UIColor colorWithRed: 234/255.0 green:234/255.0 blue: 234/255.0 alpha:1.0];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //1.设置头视图
    _headerView = [[[NSBundle mainBundle] loadNibNamed:@"ESHeaderView" owner:nil options:nil] lastObject];
    _headerView.frame = CGRectMake(0, 0, kScreenW, 270);
    _headerView.backgroundColor = [UIColor redColor];
    //2.透视图上的集合视图
    //2.1.设置集合视图布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(50, 60);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;//设置集合视图滚动的方向
    //2.2.创建集合视图
    [_headerView.collectionView setCollectionViewLayout:layout animated:YES];
    _headerView.collectionView.backgroundColor  = [UIColor whiteColor];
    _headerView.collectionView.contentSize = CGSizeMake(100000, 60);
    //2.3.设置集合视图代理
    _headerView.collectionView.dataSource = self;
    _headerView.collectionView.delegate = self;
    //2.4.注册集合视图的cell
    [_headerView.collectionView registerNib:[UINib nibWithNibName:@"ESTDCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"TDCell"];
    //3.设置表视图的头视图
    _tagDetailTableView.tableHeaderView = _headerView;
    
    //4.请求数据
    [self requestData];
    //5.创建表
    [self createTagsDetailTableView];
}

#pragma mark - 请求数据

- (void)requestData{
    //1.获得管理者
    AFHTTPRequestOperationManager *netManager = [[AFHTTPRequestOperationManager alloc] init];
    //2.设置参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"appname"] = @"baisishequ";
    parameters[@"asid"] = @"1880212C-B451-4FA7-8DFA-E07254EFCEE9";
    parameters[@"c"] = @"topic";
    parameters[@"client"] = @"iphone";
    parameters[@"device"] = [UIDevice currentDevice].model;
    parameters[@"jbk"] = @"0";
    parameters[@"mac"] = @"";
    parameters[@"market"] = @"";
    parameters[@"openudid"] = @"5a299ed728ffa000f0c4db0eb49e93d0e3968b2a";
    parameters[@"sex"] = @"m";
    parameters[@"theme_id"] = [NSString stringWithFormat:@"%@",_theme_id];
    parameters[@"udid"] = @"";
    parameters[@"uid"] = @"15094656";
    parameters[@"ver"] = @"3.6";
    //3.发送请求
    //1.头视图的数据
    parameters[@"a"] = @"theme_info";
    [netManager GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, NSDictionary *dic) {
        //直接给头视图赋值
        [_headerView.coverImageView sd_setImageWithURL:[NSURL URLWithString:dic[@"info"][@"image_detail"]]];
        _headerView.post_numberLabel.text = [NSString stringWithFormat:@"帖子数:%@",dic[@"info"][@"post_number"]];
        _headerView.sub_numberLabel.text = [NSString stringWithFormat:@"订阅人数:%@",dic[@"info"][@"sub_number"]];
        self.title = dic[@"info"][@"theme_name"];
        //刷新
        [_tagDetailTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求失败:%@",error);
    }];
    //2.集合视图数据
    parameters[@"a"] = @"theme_users";
    [netManager GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, NSDictionary *dic) {
        _topArray = [[NSMutableArray alloc] init];
        for (NSDictionary  *dic1 in dic[@"top"]) {
            ESTopModel *model = [[ESTopModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            [_topArray addObject:model];
        }
        //刷新
        [_headerView.collectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求失败:%@",error);
    }];
    //3.表视图的数据order=new&page=1&pagesize=20
    parameters[@"a"] = @"theme_datalist";
    parameters[@"order"] = @"new";
    parameters[@"page"] = @1;
    parameters[@"pagesize"] = @20;
    parameters[@"type"] = @0;
    [netManager GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, NSDictionary *dic) {
        _listArray = [[NSMutableArray alloc] init];
        for (NSDictionary  *dic1 in dic[@"list"]) {
            ESListModel *model = [[ESListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            [_listArray addObject:model];
        }
        //刷新
        [_tagDetailTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求失败:%@",error);
    }];
}
#pragma mark - 创建表

- (void)createTagsDetailTableView{
    //1.设置代理
    _tagDetailTableView.dataSource = self;
    _tagDetailTableView.delegate = self;
    //2.注册cell
    [_tagDetailTableView registerNib:[UINib nibWithNibName:@"ESTDVideoCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ESTDVideoCell"];
    [_tagDetailTableView registerNib:[UINib nibWithNibName:@"ESTDPictureCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"TDPictureCell1"];
    [_tagDetailTableView registerNib:[UINib nibWithNibName:@"ESTDDuanZiCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ESTDDuanZiCell"];
    [_tagDetailTableView registerNib:[UINib nibWithNibName:@"ESTDTextAndPicCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ESTDTextAndPicCell"];
    [_tagDetailTableView registerNib:[UINib nibWithNibName:@"ESTDVoiceCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ESTDVoiceCell"];
    //3.去掉tableView的分割线
    _tagDetailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
}
#pragma mark - 列表视图的代理方法
//1.创建1个分区和一个区头
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
    headerView.backgroundColor = [UIColor colorWithRed: 234/255.0 green:234/255.0 blue: 234/255.0 alpha:1.0];
    //在headerView上添加两个Button
    //1.最新
    UIButton *bt1 = [UIButton buttonWithType:UIButtonTypeSystem];
    bt1.frame = CGRectMake(0, 0, kScreenW * 0.5, 30);
    [bt1 setTitle:@"最新" forState:UIControlStateNormal];
    [bt1 addTarget:self action:@selector(newBT:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:bt1];
    //2.最热
    UIButton *bt2 = [UIButton buttonWithType:UIButtonTypeSystem];
    bt2.frame = CGRectMake(kScreenW * 0.5, 0, kScreenW * 0.5, 30);
    [bt2 setTitle:@"最热" forState:UIControlStateNormal];
    [bt2 addTarget:self action:@selector(hotBT:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:bt2];
    //3.创建一个条两个Button的分割线
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(kScreenW * 0.5, 0, 2, 30)];
    line.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:line];
    return headerView;
}
- (void)newBT:(UIButton *)button{
    NSLog(@"最新");
}
- (void)hotBT:(UIButton *)button{
    NSLog(@"最热");
}
//2.分区内
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[_listArray[indexPath.row] type_] isEqualToString:@"41"]) {
        //type = 41视频
        static NSString *reuseIdentifier = @"ESTDVideoCell";
        ESTDVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (cell == nil) {
            cell = [[ESTDVideoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        }
        cell.backgroundColor = [UIColor colorWithRed: 234/255.0 green:234/255.0 blue: 234/255.0 alpha:1.0];
        cell.listModel = _listArray[indexPath.row];
        return cell;
    }else if ([[_listArray[indexPath.row] type_] isEqualToString:@"10"]){
        //type = 10 图片
        static NSString *reuseIdentifier = @"TDPictureCell1";
        ESTDPictureCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (cell == nil) {
            cell = [[ESTDPictureCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        }
        cell.backgroundColor = [UIColor colorWithRed: 234/255.0 green:234/255.0 blue: 234/255.0 alpha:1.0];
        cell.listModel = _listArray[indexPath.row];
        return cell;
    }else if ([[_listArray[indexPath.row] type_] isEqualToString:@"29"]){
        //type = 29 段子
        static NSString *reuseIdentifier = @"ESTDDuanZiCell";
        ESTDDuanZiCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (cell == nil) {
            cell = [[ESTDDuanZiCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        }
        cell.backgroundColor = [UIColor colorWithRed: 234/255.0 green:234/255.0 blue: 234/255.0 alpha:1.0];
        cell.listModel = _listArray[indexPath.row];
        return cell;
    }else if([[_listArray[indexPath.row] type_] isEqualToString:@"51"]){
        //type = 51 左边文字右边图片
        static NSString *reuseIdentifier = @"ESTDTextAndPicCell";
        ESTDTextAndPicCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (cell == nil) {
            cell = [[ESTDTextAndPicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        }
        cell.backgroundColor = [UIColor colorWithRed: 234/255.0 green:234/255.0 blue: 234/255.0 alpha:1.0];
        cell.listModel = _listArray[indexPath.row];
        return cell;
    }else{
        //type = 31 声音
        static NSString *reuseIdentifier = @"ESTDVoiceCell";
        ESTDVoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (cell == nil) {
            cell = [[ESTDVoiceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        }
        cell.backgroundColor = [UIColor colorWithRed: 234/255.0 green:234/255.0 blue: 234/255.0 alpha:1.0];
        cell.listModel = _listArray[indexPath.row];
        return cell;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[_listArray[indexPath.row] type_] isEqualToString:@"41"]) {
        //type = 41视频
        //模态显示播放器
        NSURL *url = [NSURL URLWithString:[_listArray[indexPath.row] videouri]];
        MoviePlayerViewController *movieVC = [[MoviePlayerViewController alloc]initNetworkMoviePlayerViewControllerWithURL:url movieTitle:[_listArray[indexPath.row] theme_name]];
        movieVC.datasource = self;
        [self presentViewController:movieVC animated:YES completion:nil];
        
    }else if ([[_listArray[indexPath.row] type_] isEqualToString:@"10"]){
        //type = 10 图片
        ESDT2ViewController *DTVC = [[ESDT2ViewController alloc] init];
        DTVC.weixin_url = [_listArray[indexPath.row] weixin_url];
        [self.navigationController pushViewController:DTVC animated:YES];
        
    }else if ([[_listArray[indexPath.row] type_] isEqualToString:@"29"]){
        //type = 29 段子
        ESDT2ViewController *DTVC = [[ESDT2ViewController alloc] init];
        [self.navigationController pushViewController:DTVC animated:YES];
        DTVC.weixin_url = [_listArray[indexPath.row] weixin_url];
    }else if([[_listArray[indexPath.row] type_] isEqualToString:@"51"]){
        //type = 51 左边文字右边图片
        ESDT2ViewController *DTVC = [[ESDT2ViewController alloc] init];
        DTVC.weixin_url = [_listArray[indexPath.row] weixin_url];
        [self.navigationController pushViewController:DTVC animated:YES];
    }else{
        //type = 31 声音
        NSURL *url = [NSURL URLWithString:[_listArray[indexPath.row] voiceuri]];
        MoviePlayerViewController *movieVC = [[MoviePlayerViewController alloc]initNetworkMoviePlayerViewControllerWithURL:url movieTitle:[_listArray[indexPath.row] theme_name]];
        movieVC.datasource = self;
        [self presentViewController:movieVC animated:YES completion:nil];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[_listArray[indexPath.row] type_] isEqualToString:@"41"]) {
        //type = 41视频
        int cell_height = ([[_listArray[indexPath.row] height_] intValue] * kScreenW ) / [[_listArray[indexPath.row] width_] intValue] + 120;
        return cell_height;
        
    }else if ([[_listArray[indexPath.row] type_] isEqualToString:@"10"]){
        //type = 10 图片
        int cell_height = ([[_listArray[indexPath.row] height_] intValue] * kScreenW )/ [[_listArray[indexPath.row] width_] intValue] + 120;
        return cell_height;
    }else if ([[_listArray[indexPath.row] type_] isEqualToString:@"29"]){
        //type = 29 段子
        CGFloat DuanZi_height = [self heightForString:[_listArray[indexPath.row] content]] + 180;
        return DuanZi_height;
    }else if([[_listArray[indexPath.row] type_] isEqualToString:@"51"]){
        //type = 51 左边文字右边图片
        return 230;
    }else{
        //type = 31 声音
        int cell_height = ([[_listArray[indexPath.row] height_] intValue] * kScreenW ) / [[_listArray[indexPath.row] width_] intValue] + 120;
        return cell_height;
    }
}
//文本的高度
- (CGFloat)heightForString:(NSString *)str{
    NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:[UIFont systemFontOfSize:15],NSFontAttributeName, nil];
    
    CGRect rect = [str boundingRectWithSize:CGSizeMake(304,1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}

#pragma mark - 头视图上的集合视图代理方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _topArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ESTDCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TDCell" forIndexPath:indexPath];
    cell.topModel = _topArray[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"love");
}
#pragma mark - 推出播放器

//- (void)playNetMovie{
//    NSString *path = [DBTool readPathTitle:_fileName];
//    if (![path isEqualToString:@""]) {//缓存中有播放资源,播放本地缓存视频
//        NSLog(@"缓存中有播放资源,播放本地缓存视频");
//        NSURL *url = [NSURL fileURLWithPath:path];
//        MoviePlayerViewController *movieVC = [[MoviePlayerViewController alloc]initLocalMoviePlayerViewControllerWithURL:url movieTitle:_openEyesModel.title];
//        [self presentViewController:movieVC animated:YES completion:nil];
//    } else {//没有缓存,根据playerurl播放网络视频
//        NSLog(@"没有缓存,根据playerurl播放网络视频");
//        NSURL *url = [NSURL URLWithString:_openEyesModel.playUrl];
//        MoviePlayerViewController *movieVC = [[MoviePlayerViewController alloc]initNetworkMoviePlayerViewControllerWithURL:url movieTitle:_openEyesModel.title];
//        movieVC.datasource = self;
//        [self presentViewController:movieVC animated:YES completion:nil];
//    }
//    
//}

#pragma mark - 播放器代理方法
- (NSDictionary *)previousMovieURLAndTitleToTheCurrentMovie{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSURL URLWithString:@"http://v.youku.com/player/getRealM3U8/vid/XNjQ5MDM3Nzg0/type/mp4/v.m3u8"],KURLOfMovieDicTionary,@"qqqqqqq",KTitleOfMovieDictionary, nil];
    return dic;
}
- (NSDictionary *)nextMovieURLAndTitleToTheCurrentMovie{
    return nil;
}
- (BOOL)isHavePreviousMovie{
    return NO;
}
- (BOOL)isHaveNextMovie{
    return NO;
}

@end
